package fr.cephb.util;

import java.util.Collection;

public class StringUtils
	{
	/** returns wether the string is null or contains only white char */
	public static boolean isEmpty(String s)
		{
		if(s==null || s.length()==0) return true;
		for(int i=0;i< s.length();++i)
			{
			if(!Character.isWhitespace(s.charAt(i))) return false;
			}
		return true;
		}
	
	public static String escape(String s)
		{
		 StringBuilder buffer=new StringBuilder(s.length());
        for(int i=0;i< s.length();++i)
            {
            switch(s.charAt(i))
                {
                case('\"'): buffer.append("\\\"");break;
                case('\''): buffer.append("\\\'");break;
                case('\n'): buffer.append("\\n");break;
                case('\t'): buffer.append("\\t");break;
                case('\\'): buffer.append("\\\\");break;
                default: buffer.append(s.charAt(i)); break;
                }
            }
        return buffer.toString();
		}
	
	public static String unescape(String s)
		{
		if(s==null) return null;
      	StringBuilder sb= new StringBuilder(s.length());
      	for(int i=0;i< s.length();++i)
      		{
      		if(s.charAt(i)=='\\')
    			{
    			if(i+1< s.length())
    				{
    				++i;
    				switch(s.charAt(i))
    					{
    					case 'n': sb.append('\n'); break;
    					case 'r': sb.append('\r'); break;
    					case '\\': sb.append('\\'); break;
    					case 'b': sb.append('\b'); break;
    					case 't': sb.append('\t'); break;
    					case 'f': sb.append('\f'); break;
    					case '\'': sb.append('\''); break;
    					case '\"': sb.append('\"'); break;
    					default: sb.append(s.charAt(i));
    					}
    				}
      			}
      		else
      			{
      			sb.append(s.charAt(i));
      			}
      		}
      	return sb.toString();
		}
	public static String join(final Collection<?> col,String delim)
		{
		StringBuilder b=new StringBuilder();
		boolean first=true;
		for(Object o:col)
			{
			if(!first) b.append(delim);
			first=false;
			b.append(String.valueOf(o));
			}
		return b.toString();
		}
	}
